package leecode.数组和字符串.KMP算法;

public class KMP {
    public static void main(String[] args) {
        String str1 = "BBC ABCDAB ABCDABCDABDE";
        String str2 = "ABCDABD";
        int[] next = kmpNext(str2);
        int i = kmpSearch(str1, str2, next);
        System.out.println(i);

    }

    public static int kmpSearch(String str1, String str2, int[] next) {
        for(int i = 0, j = 0; i < str1.length(); i++) {
            //不相等时
            while( j > 0 && str1.charAt(i) != str2.charAt(j)) {
                j = next[j-1]; //往前看
            }
            if(str1.charAt(i) == str2.charAt(j)) {
                j++;
            }
            if(j == str2.length()) {
                return i - j + 1;
            }
        }
        return -1;
    }

    //获取一个子串的部分匹配值
    public static int[] kmpNext(String dest) {
        //创建一个next数组
        int[] next = new int[dest.length()];
        next[0] = 0; //字符串长度为1时匹配值为0,或首字符匹配值为0
        //寻找最长公共前后缀，算法核心
        for (int i = 1, j = 0; i < dest.length(); i++) {
            if (dest.charAt(i) != dest.charAt(j)) {//不匹配时，我们需要从next[j-1]获取j值 直到相等时退出
                while (j > 0 && dest.charAt(i) != dest.charAt(j)) {
                    j = next[j - 1]; //往前看
                }

            }
            if (dest.charAt(i) == dest.charAt(j)) {//当字符相等时，匹配值+1
                j++;
            }
            next[i] = j;

        }
        return next;
    }
}
